import { createStore } from 'vuex'

// 创建一个新的 store 实例
export default createStore({
  state() {
    return {
      tabList: [],
      // 当前选项卡id,也就是path
      currentContextTabId: ''
    }
  },
  mutations: {
    // 添加rab
    addTab(state, ItemTab) {
      const isSome = state.tabList.some(item => item.path == ItemTab.path)
      if (!isSome) {
        state.tabList.push(ItemTab)
      }
    },
    // 删除tab
    closeCurrentTab(state, targetName) {
      const index = state.tabList.findIndex(item => item.path === targetName)
      state.tabList.splice(index, 1)
    },
    // 刷新保存页面的tab数据
    refresh(state, list) {
      state.tabList = list
    },
    // 保留当前id{
    saveCurrentContextTabId(state, id) {
      state.currentContextTabId = id
    },
    // 关闭所有
    closeAllTabs(state) {
      state.tabList = []
      sessionStorage.removeItem('tabs_routes')
    },
    //关闭其他
    closeOtherTabs(state, type) {
      if (type === 'other') {
        // 列表里只留下当前id,也就是当前path
        state.tabList = state.tabList.filter(item => item.path == state.currentContextTabId)
      } else if (type === 'left') {
        console.log(type);
        //如果是删除左边,那就比如第三个,索引是2,那么就slice
        let index = state.tabList.findIndex(item => item.path == state.currentContextTabId)
        // 比如当前第三个, 从0开始删, 删2个
        state.tabList.splice(0, index)
      } else if (type === 'right') {
        console.log(type);
        let index = state.tabList.findIndex(item => item.path == state.currentContextTabId)
        // 比如当前第三个, 从index开始删,也就是2,所以要加1
        state.tabList.splice(index + 1)
      }
    }

  },
  getters: {
    getAddTab(state) {
      return state.tabList
    }
  }
})